<script setup>
defineOptions({
  name: 'EditUserModal',
});
import { getUserPage, saveUser, deleteUser, getUserDetail } from '@/api/user';
import { getAllRoles } from '@/api/role';
import { useFormModalContext } from '@/hooks/modal/useFormModal';
import { useTemplateRef } from 'vue';
const { props, resolve, reject } = useFormModalContext();

const rules = {
  username: [{ required: true, message: '请输入用户名' }],
  // nickname: [{ required: true, message: '请输入昵称' }],
  // email: [{ required: true, message: '请输入邮箱' }],
  // phone: [{ required: true, message: '请输入手机号' }],
  password: [{ required: true, message: '请输入密码' }],
  roleIds: [{ required: true, message: '请选择角色' }],
};
const formState = reactive({
  ...props,
});
const roleOptions = ref([]);
const formRef = useTemplateRef('formRef');

const loadRoles = async () => {
  try {
    const response = await getAllRoles();
    roleOptions.value = response.data || response || [];
  } catch (error) {
    console.error('加载角色列表失败:', error);
  }
};
loadRoles();
const handleCancel = () => {
  reject();
};
const handleConfirm = async () => {
  if (formRef.value) {
    formRef.value.validate().then(() => {
      resolve(formState);
    });
  }
};
</script>

<template>
  <y-form-modal>
    <a-form
      :model="formState"
      :rules="rules"
      ref="formRef"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="用户名" name="username">
        <a-input
          v-model:value="formState.username"
          placeholder="请输入用户名"
        />
      </a-form-item>

      <a-form-item label="昵称" name="nickname">
        <a-input v-model:value="formState.nickname" placeholder="请输入昵称" />
      </a-form-item>

      <a-form-item label="邮箱" name="email">
        <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
      </a-form-item>

      <a-form-item label="手机号" name="phone">
        <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
      </a-form-item>

      <a-form-item v-if="!formState.id" label="密码" name="password">
        <a-input-password
          v-model:value="formState.password"
          placeholder="请输入密码"
        />
      </a-form-item>

      <a-form-item label="角色" name="roleIds">
        <a-select
          v-model:value="formState.roleIds"
          mode="multiple"
          placeholder="请选择角色"
          :options="roleOptions"
          :field-names="{ label: 'name', value: 'id' }"
        />
      </a-form-item>

      <a-form-item label="状态" name="status">
         <YLocalSelect v-model="formState.status" option="USER_STATUS_OPTIONS"></YLocalSelect>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleConfirm">确认</a-button>
      </a-space>
    </template>
  </y-form-modal>
</template>
